import XEUtils from 'xe-utils';
import _ from 'lodash-es';
/**
 * @desc 解决浮动运算问题，避免小数点后产生多位数和计算精度损失。
 * 问题示例：2.3 + 2.4 = 4.699999999999999，1.0 - 0.9 = 0.09999999999999998
 */

/**
 * 精确乘法
 */
function times(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return times(times(num1, num2), others[0], ...others.slice(1));
  }

  return XEUtils.multiply(num1, num2);
}

/**
 * 精确加法
 */
function plus(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return plus(plus(num1, num2), others[0], ...others.slice(1));
  }

  return XEUtils.add(num1, num2);
}

/**
 * 精确减法
 */
function minus(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return minus(minus(num1, num2), others[0], ...others.slice(1));
  }

  return XEUtils.subtract(num1, num2);
}

/**
 * 精确除法
 */
function divide(num1: number, num2: number, ...others: number[]): number {
  if (others.length > 0) {
    return divide(divide(num1, num2), others[0], ...others.slice(1));
  }
  return XEUtils.divide(num1, num2);
}

/**
 * 四舍五入
 */
function round(num: number, ratio: number): number {
  return _.round(num, ratio);
}

export { plus, minus, times, divide, round };
export default {
  plus,
  minus,
  times,
  divide,
  round,
};
